<?php

/* * *******
 *    首页控制器
 */

namespace Home\Controller;

use Home\Controller\HomeController;

class GoodsController extends HomeController {

	public function _initialize(){
		parent::_initialize();
		
	}
	
    /**
     * 查询所有主分类
     */
    public function getGoodsCat() {
        $cat = M('Cat')->where('pid =' . "0")->select();
        $this->ajaxReturn($cat, 'JSONP');
    }

    /**
     * 查询子分类
     */
    public function getGoodsCatByPid() {
        $pid = I('pid');
        $cat = M('Cat')->where('pid =' . $pid)->select();
        foreach ($cat as &$v) {
            $v['cat'] = M('Cat')->where('pid =' . $v['cat_id'])->select();
        }
        $this->ajaxReturn($cat, 'JSONP');
    }

    /**
     * 根据分类获取商品
     */
    public function getGoodsByCat() {
	    // dump(123);
        $cat_id = I('cat_id') ? I('cat_id') : null;
        $page = I('page') ? I('page') : null;
        $goods = M('Goods')->where(array('cat_id' => $cat_id, 'is_sale' => 1))->select();
        foreach ($goods as &$v) {
            $price = M('Goods_attr')->where(array('goods_id' => $v['goods_id'], 'is_price_main' => 1))->find();
            $v['price'] = $price['price'];
            $v['jifen'] = $price['jifen'];
        }
	       
        $this->ajaxReturn($goods, 'JSONP');
    }

    /**
     * 获取热门搜索
     * 
     */
    public function getHotSearch() {
        $search[] = M("Config")->where(array("key" => 'SEARCH_ONE'))->find()['value'];
        $search[] = M("Config")->where(array("key" => 'SEARCH_TWO'))->find()['value'];
        $search[] = M("Config")->where(array("key" => 'SEARCH_THREE'))->find()['value'];
        $search[] = M("Config")->where(array("key" => 'SEARCH_FOUR'))->find()['value'];
        $this->ajaxReturn($search, 'JSONP');
    }
    //拼抢首页
    public function getGoodsList(){
        $goods['goods'] = M('Goods')->where(array('is_sale' => 1, 'is_limit' => 1))->select();
//        dump($goods['goods']);
        foreach($goods['goods'] as &$v){
            $v['orders']= M('rob_goods_orders')->where(array('goods_id'=>$v['goods_id'],'is_price_main'=>1))->find();
        //查询多少人在拼抢
            if(time()<$v['start_time']){
            	$v['zhuangtai']=-5;//未开始
            }else{
            	$v['zhuangtai']=1;
            	$v['start_time']=time();
            }
            if(time()>$v['end_time']){
            	$v['zhuangtai']=-4;//已结束
            }
            $dat['goods_id']=$v['goods_id'];
            $v['ren']=M('rob_goods_orders')->where($dat)->Count();
        }
        $goods['openid']=$open;
        $this->ajaxReturn($goods);
    }

    /**
     * 查看商品详情
     */
    public function getGoodsDetails() {
        $goods_id = I('goods_id');
        $open_id = I('openid');
        if($open_id){
            $da['goods_id']=$goods_id;
            $da['open_id']=$open_id;
        }else{
            $da['goods_id']=$goods_id;
        }
        $goods['goas'] = M('Goods')->where(array('goods_id' => $goods_id, 'is_sale' => 1, 'is_limit' => 1))->find();
        $goods['goas']['start_time']=(string)time();
        if((int)$goods['goas']['end_time']-(int)$goods['goas']['start_time']<=0){
        	$goods['goas']['end_time']=0;
        	$goods['goas']['start_time']=0;
        }
        //查询商品状态  是否拼抢过  MAXNUM次
        $over1=M('rob_orders')->join('left join yang_rob_goods_orders on yang_rob_goods_orders.order_id = yang_rob_orders.order_id')->where(array('goods_id' => $goods_id, 'open_id'=>$open_id))->count();
        $c1=M('config');
        $chu1=$c1->select();
        //dump($chu1);
        $num11=0;
        foreach($chu1 as $k1=>$v1){
        	if($v1['key']=='MAXNUM'){
        		$num11=$v1['value'];
        	}
        }
        //echo $num11;
        //echo $over1;
        $goods['openid']=$open_id;
        if($over1>=$num11){
        	$goods['pinqiang']='-2';
        	$goods['over1']=$over1;
        	$goods['num11']=$num11;
        }else{
        	$goods['pinqiang']='-1';
        	$goods['over1']=$over1;
        	$goods['num11']=$num11;
        }
        $over=M('rob_orders')->join('left join yang_rob_goods_orders on yang_rob_goods_orders.order_id = yang_rob_orders.order_id')
                ->where($da)->find();
        if(!empty($over)){
           $goods['over']=1;
           $goods['order_id']=$over['order_id'];
        }else{
            $goods['over']=0;
            $goods['order_id']=0;
        }
        $goods['pic'] = M('Goods_pic')->where(array('goods_id' => $goods_id))->select();
        $goods['attr'] = M('Goods_attr')->where(array('goods_id' => $goods_id))->group('attr_id')->select();

        foreach ($goods['attr'] as &$v) {
            $name = M('Attr')->where(array('attr_id' => $v['attr_id']))->find();
            $v['name'] = $name['name'];
            if (($v['price'] != null && $v['price'] != 0) || ($v['jifen'] != null && $v['jifen'] != 0)) {
                $v['attr'] = M('Goods_attr')->where(array('goods_id' => $goods_id, 'attr_id' => $v['attr_id']))->select();
            } else {
                $attr = M('Goods_attr')->where(array('goods_id' => $goods_id, 'attr_id' => $v['attr_id']))->find();
                foreach (explode(',', $attr['attr_val']) as &$s) {
                    $v['attr'][]['attr_val'] = $s;
                }
            }
        }
        $goods['kucun'] = M('Goods_attr')->where(array('goods_id' => $goods_id))->sum('attr_kucun');
        $price = M('Goods_attr')->where(array('goods_id' => $goods_id, 'is_price_main' => 1))->find();
        //有人在抢购
         $qea['goods_id']=$goods_id;
        $uqs=M('rob_goods_orders')->where($qea)->count();
        $goods['order_price'] = $goods['goas']['old_price'];
        $goods['jifen'] = $price['jifen'];
        $goods['price'] =$goods['goas']['goods_price'];
        $goods['fanjifen'] = $price['fanjifen'];
        $goods['zren'] = $uqs;
        $year = date('y', time());
        $mouth = date('m', time());
        $month_count = M('Count_month')->where(array('goods_id' => $goods_id, 'year' => $year, 'month' => $mouth))->find();
        if (!$month_count) {
            $data = [
                'goods_id' => $goods_id,
                'count' => 0,
                'year' => $year,
                'month' => $mouth,
            ];
            M('Count_month')->add($data);
            $goods['month_count'] = 0;
        } else {
            $goods['month_count'] = $month_count['count'];
        }

        $goods['content_all'] = html_entity_decode($goods['content_all']);
        $a_array = explode('<', $goods['content_all']);
        foreach ($a_array as $k => &$v) {
            $v = substr_replace($v, 'http://sc-wscjf.91quyum.com', 9, 0);
            if ($k != 0) {
                $array_last[] = $v;
            }
        }
        $rob_rule=M('rob_rule')->where(array('type'=>0))->find();
        $goods['rule']=$rob_rule['content'];
        //dump($goods['attr']);die;
        $this->ajaxReturn($goods);
    }

    /**
     * 获取搜索历史记录
     */
    public function getSearchHistory() {
        $open_id = session('openid');
        $history = M('Search')->where(array('open_id' => $open_id))->order('add_time desc')->limit(5)->select();
        $this->ajaxReturn($history, 'JSONP');
    }

    /**
     * 搜索商品
     */
    public function searchGoodsByKeywords() {
        $open_id = session('openid');
        $keywords = I('keywords');
        //排序
        $count_month = I('count_month');
        $price = I('price');
        $pingjia = I('pingjia');
        $price_shai1 = I('price_shai1');
        $price_shai2 = I('price_shai2');
        $cat_id = I('cat_id');
        if ($count_month) {
            $order = "count desc";
        }
        if ($price) {
            $order = "ga.price asc";
        }
        if ($price_shai1 && $price_shai1) {
            $where['price'] = array('between', $price_shai1 . 'and' . $price_shai2);
        }
        //查询分类
        $goods = [];
        $goods_array = [];
        if ($keywords != "") {
            $where_cat['name'] = array('like', '%' . $keywords . '%');
        }

        $cats = M('Cat')->where($where_cat)->select();
        if ($cats) {
            foreach ($cats as $v) {
                $good = M('Goods')->where(array('cat_id' => $v['cat_id'], 'is_sale' => 1))->select();
                if ($good) {
                    foreach ($good as &$q) {
                        $price = M('Goods_attr')->where(array('goods_id' => $q['goods_id'], 'is_price_main' => 1))->find();
                        $q['price'] = $price['price'];
                        $q['jifen'] = $price['jifen'];
                        $goods[] = $q;
                        $goods_array[] = $q['goods_id'];
                    }
                }
            }
        }
        $where['_string'] = ' (name like "%' . $keywords . '%")   ';
        //$where['g.name'] = array("like", "%".$keywords."%");
        $where['ga.is_price_main'] = 1;
        if ($cat_id) {
            $where['g.cat_id'] = $cat_id;
        }
        $where['is_sale'] = 1;

        $goods = M('Goods g')
                        ->field("g.*,ga.*")
                        ->join('yang_goods_attr ga ON ga.goods_id = g.goods_id')
                        ->join('yang_count_month cm ON cm.goods_id = g.goods_id', 'left')
                        ->order($order)
                        ->where($where)->select();

        if ($pingjia) {
            /* $goods = M('Goods g')
              ->field('g.*,count(c.goods_id) as comment,ga.*,cm.*')
              ->join('yang_goods_attr ga ON ga.goods_id = g.goods_id','left')
              ->join('yang_count_month cm ON cm.goods_id = g.goods_id','left')
              ->join('yang_comment c ON c.goods_id =g.goods_id','left')
              ->order("comment desc")
              ->where($where)->select(); */
            $sql = "select g.*,ga.*, c.*,avg(c.score) as score from yang_goods g 
		         left join yang_goods_attr ga ON ga.goods_id = g.goods_id 
		         left join yang_comment c ON c.goods_id =g.goods_id  ";

            if ($where['ga.is_price_main'] = 1) {
                $sql .= " where ga.is_price_main = 1 and is_sale = 1 ";
            }
            if ($keywords) {
                $sql .= " and  g.name like '%" . $keywords . "%' ";
            }
            if ($cat_id) {
                $sql .= " and g.cat_id =" . $cat_id;
            }
            $sql .= " group by c.goods_id order by score desc ";
            $goods = M()->query($sql);
        }

        /* echo M("Goods g")->_sql();
          if($good_select){
          foreach ($good_select as &$c){
          if(!in_array($c['goods_id'], $goods_array)){
          $price = M('Goods_attr')->where(array('goods_id'=>$c['goods_id'],'is_price_main'=>1))->find();
          $count_month = M('Count_month')->where(array('goods_id'=>$c['goods_id']))->find()['count'];
          if($count_month){
          $c['count_month'] = $count_month;
          }
          $c['price'] = $price['price'];
          $c['jifen'] = $price['jifen'];
          $goods[] = $c;
          $goods_array[] = $c['goods_id'];
          }
          }
          } */
        //$goods[] = $good_select;
        //添加到搜索记录表
        $search_find = M('Search')->where(array('open_id' => $open_id, 'value' => $keywords))->find();
        if ($search_find) {
            M('Search')->where(array('open_id' => $open_id, 'value' => $keywords))->setInc('num', 1);
            M('Search')->where(array('open_id' => $open_id, 'value' => $keywords))->setField('add_time', time());
        } else {
            if ($keywords != "") {
                $search = [
                    'open_id' => $open_id,
                    'value' => $keywords,
                    'add_time' => time(),
                    'num' => 1,
                ];
                M('Search')->add($search);
            }
        }

        $this->ajaxReturn($goods, 'JSONP');
    }

    public function getRexiao() {
        $year = date('y', time());
        $mouth = date('m', time());
        $month_count = M('Count_month cm')
                ->join("yang_goods g ON g.goods_id = cm.goods_id")
                ->where(array('year' => $year, 'month' => $mouth, 'is_sale' => 1))
                ->order('count desc')
                ->select();
        foreach ($month_count as &$v) {
            $price = M('Goods_attr')->where(array('goods_id' => $v['goods_id'], 'is_price_main' => 1))->find();
            $v['price'] = $price['price'];
            $v['jifen'] = $price['jifen'];
            $v['fanjifen'] = $price['fanjifen'];
        }
        $this->ajaxReturn($month_count, 'JSONP');
    }

    public function getTuijian() {
        $goods = M('Goods')
                ->where(array('is_tuijian' => 1, 'is_sale' => 1))
                ->select();
        foreach ($goods as &$v) {
            $price = M('Goods_attr')->where(array('goods_id' => $v['goods_id'], 'is_price_main' => 1))->find();
            $v['price'] = $price['price'];
            $v['jifen'] = $price['jifen'];
            $v['fanjifen'] = $price['fanjifen'];
        }
        $this->ajaxReturn($goods, 'JSONP');
    }

    //删除搜索记录
    public function delSearch() {
        $open_id = session('openid');
        $r = M('Search')->where(array('open_id' => $open_id))->delete();
        if ($r) {
            $this->ajaxReturn(['status' => 1, 'msg' => '删除成功'], 'JSONP');
        }
    }

}
